package com.xn.app.muying;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.jumper.fetalheart.ADFetalHeart;
import com.jumper.fetalheart.ConnectCallback;
import com.jumper.fetalheart.Mode;
import com.jumper.fetalheart.blue.CheckDevicesCallback;
import com.jumper.fetalheart.line.HeadSetUnit;

import java.util.ArrayList;
import java.util.List;

public class LianJieActivity extends AppCompatActivity {
    private String TAG = this.getClass().getSimpleName();
    private Button you_xian, lan_ya;
    private ListView mListView;
    private static final int SCANNING = 1;
    private static final int STOP_SCAN = -1;
    /**
     * 获取蓝牙适配器
     */
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    //
    private BlueDeviceAdapter mBlueDeviceAdapter;
    private BlueBroadCastRecever mBlueBroadCastRecever;
    private Handler handler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            return false;
        }
    });
    private ADFetalHeart mAdFetalHeart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lian_jie);
        you_xian = (Button) findViewById(R.id.you_xian);
        lan_ya = (Button) findViewById(R.id.lan_ya);
        findViewById(R.id.guan_bi).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //获得天使医生胎心操作类
        mAdFetalHeart = ADFetalHeart.getInstance(this);
        mBlueDeviceAdapter = new BlueDeviceAdapter(this);
        mListView = (ListView) findViewById(R.id.bl_list);
        mListView.setAdapter(mBlueDeviceAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BluetoothDevice mBtDevice = (BluetoothDevice) parent.getItemAtPosition(position);
                // 尝试连接蓝牙设备
                mAdFetalHeart.connect(mBtDevice);
            }
        });
        you_xian.setOnClickListener(onClickListener);
        lan_ya.setOnClickListener(onClickListener);
        // 注册蓝牙扫描广播接收者
        mBlueBroadCastRecever = new BlueBroadCastRecever();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mBlueBroadCastRecever, intentFilter);
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Drawable yx1 = getResources().getDrawable(R.mipmap.img_0022);
            Drawable yx2 = getResources().getDrawable(R.mipmap.img_0023);
            Drawable ly1 = getResources().getDrawable(R.mipmap.img_0024);
            Drawable ly2 = getResources().getDrawable(R.mipmap.img_0025);
            switch (v.getId()) {
                case R.id.you_xian:
                    you_xian.setCompoundDrawablesWithIntrinsicBounds(null, yx2 , null, null);
                    lan_ya.setCompoundDrawablesWithIntrinsicBounds(null, ly1 , null, null);
                    // 设置成 有线模式
                    mAdFetalHeart.setMode(Mode.LINE);
                    // 检查耳机音频线是否有插入
                    if (HeadSetUnit.checkHeadSet(LianJieActivity.this)) {
                        //连接成功
                        startActivity(new Intent(LianJieActivity.this, RecordingActivity.class));
                    } else {
                        //无耳机插入
                        startActivity(new Intent(LianJieActivity.this, YouXianActivity.class));
                    }
                    break;
                case R.id.lan_ya:
                    you_xian.setCompoundDrawablesWithIntrinsicBounds(null, yx1 , null, null);
                    lan_ya.setCompoundDrawablesWithIntrinsicBounds(null, ly2 , null, null);
                    mBlueDeviceAdapter.clear();
                    // 设置 成 蓝牙模式
                    mAdFetalHeart.setMode(Mode.BLUE);
                    startDiscovery();
                    break;
            }
        }
    };
    ConnectCallback connectCallback = new ConnectCallback() {
        @Override
        public void onConnectSuccess() {
            Log.d(TAG, "获取到数据");
            startActivity(new Intent(LianJieActivity.this, RecordingActivity.class));
        }

        //  这里setting 是用来判断此设备是否需要跳到设置界面配对
        // 如果为 true就说明得先跳到设置界面
        // false 就说明设备连接失败（蓝牙的，也包括有线在使用过程中断线）
        @Override
        public void onConnectFail(boolean setting) {
            Log.d(TAG, "连接失败");
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        mAdFetalHeart.setConnectCallback(connectCallback);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mAdFetalHeart.setConnectCallback(null);
    }

    private class BlueBroadCastRecever extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // 搜索到蓝牙设备
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Log.d("Terry", "device -->[" + device.getName() + "] " + device.getAddress());
                mBlueDeviceAdapter.addDevices(device);
                // 扫描停止广播
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                handler.sendEmptyMessage(STOP_SCAN);
            }
        }
    }

    //开始搜索蓝牙设备
    private void startDiscovery() {
        mAdFetalHeart.checkDevices(new CheckDevicesCallback() {
            @Override
            public void onFindDevice(BluetoothDevice device) {
                mBlueDeviceAdapter.addDevices(device);
            }
        });
        mBluetoothAdapter.startDiscovery();
        handler.sendEmptyMessage(SCANNING);
        cancelDiscoveryDelay();
    }

    protected void cancelDiscovery() {
        mBluetoothAdapter.cancelDiscovery();
        handler.sendEmptyMessage(STOP_SCAN);
        handler.removeCallbacks(runnable);
    }

    protected void cancelDiscoveryDelay() {
        handler.postDelayed(runnable, 60000);
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            cancelDiscovery();
        }
    };

    private class BlueDeviceAdapter extends BaseAdapter {
        private LayoutInflater mInflater;
        private List<BluetoothDevice> devices;

        public BlueDeviceAdapter(Context context) {
            mInflater = LayoutInflater.from(context);
            devices = new ArrayList<>();
        }

        public void addDevices(BluetoothDevice bluetoothDevice) {
            if (!devices.contains(bluetoothDevice)) {
                devices.add(bluetoothDevice);
                notifyDataSetChanged();
            }
        }

        @Override
        public int getCount() {
            return devices.size();
        }

        @Override
        public Object getItem(int position) {
            return devices.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_fhrdevice_layout, parent, false);
                holder = new ViewHolder();
                holder.tvBlueDeviceName = (TextView) convertView.findViewById(R.id.tvBlueDeviceName);
                holder.ivBlueConnectingState = (ImageView) convertView.findViewById(R.id.ivBlueConnecteState);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }


            if (position < devices.size())
                holder.tvBlueDeviceName.setText(
                        "[" + devices.get(position).getName() + "] "
                                + devices.get(position).getAddress()
                );
            return convertView;
        }

        private void clear() {
            devices.clear();
            notifyDataSetChanged();
        }
    }


    private static class ViewHolder {
        TextView tvBlueDeviceName;
        ImageView ivBlueConnectingState;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBlueBroadCastRecever);
        // 做一些清理工作
        // ADFetalHeart为单例，所以只要在开始初始化的activity 里做一次清理就可
        mAdFetalHeart.onDestroy();
    }
}
